import React, { Dispatch, SetStateAction, useContext, useEffect, useRef } from 'react';
import { CheckboxGroupSetValue, UseCheckboxGroupContext } from './checkboxGroup';
import classNames from 'classnames';

export type CheckboxLabel = string;

export interface CheckboxProps {
    value?: boolean
    setValue?: Dispatch<SetStateAction<boolean>>
    label: CheckboxLabel
    disabled?: boolean
    setGroupValue?: CheckboxGroupSetValue
    onClick?: () => void
}



const Checkbox: React.FC<CheckboxProps> = (props) => {

    const { value, label, disabled, setValue } = props;

    // 当父级使用了CheckBoxGroup,则走的checked.current这一套逻辑
    let checked = useRef<boolean | 'init'>('init');

    const { checkboxGroupValue, setGroupValue } = useContext(UseCheckboxGroupContext);


    const handleChecked = () => {
        // 如果是禁用状态，则不能点击
        if (disabled) {
            return false;
        }
        if (checked.current !== 'init') {
            if (setGroupValue && checkboxGroupValue) {
                checked.current === true ? setGroupValue([...checkboxGroupValue.filter(item => item !== label)]) : setGroupValue([...checkboxGroupValue, label])
            }
            checked.current = !checked.current;
        } else {
            if (setGroupValue && checkboxGroupValue) {
                !value ? setGroupValue([...checkboxGroupValue, label]) : setGroupValue([...checkboxGroupValue, label])
            }
            setValue && setValue(!value);
        }
    }


    const styles = (): React.CSSProperties => {
        return { '--cursor--': disabled ? 'not-allowed' : 'pointer' } as React.CSSProperties
    }

    const checkedClass = classNames('yulang-checkbox-content', {
        'is-checked': value || checked.current === true
    })

    useEffect(() => {
        if (checkboxGroupValue) {
            if (checkboxGroupValue.find(item => item === label)) {
                checked.current = true;
            } else {
                checked.current = false;
            }
        }
    })

    return <div className={'yulang-checkbox-container'} style={styles()} onClick={handleChecked}>
        <div className={'yulang-checkbox-content-container'}>
            <div className={checkedClass}></div>
        </div>
        {label}
    </div>
}

Checkbox.defaultProps = {
    disabled: false
}

export default Checkbox;